import React, {useState} from "react";
import logoImg from "../assets/img/logo.jpg";
import { CaretDownOutlined } from "@ant-design/icons";
import { Dropdown, Menu, Space, message} from "antd";
import defaultAvatar from '../assets/img/defaultAvatar.jpg'
import { useEffect } from "react";
import { useNavigate } from 'react-router-dom'
export default function Header() {
  const navigate = useNavigate()
  const [avatar, setAvatar] = useState(defaultAvatar)
  const [userName, setUserName] = useState("游客")
  // 模拟componentDidMount
  useEffect(()=>{
    let usename1= localStorage.getItem('username')
    let avatar1= localStorage.getItem('avatar')
    if(usename1){
      setUserName(usename1)
    }
    if(avatar1){
      setAvatar('http://192.168.1.108:3000/'+usename1)
    }
  })
  // 退出登录
  const logout = (()=>{
    localStorage.clear();// 清除localStorage中的数据，token
    message.success('退出成功，即将返回登录页')
    setTimeout(()=>navigate('/login'),1500)
  })
  const menu = (
    <Menu className="mymenu"
      items={[
        {
          key: "1",
          label: (
            // <a
            //   target="_blank"
            //   rel="noopener noreferrer"
            //   href="https://www.antgroup.com"
            // >
            //   修改资料
            // </a>
            <div>修改资料</div>
          ),
        },
        {
            type: 'divider',
          },
        {
          key: "2",
          label: (
            <div onClick={logout}>退出登录</div>
          ),
        }
      ]}
    />
  );
  return (
    <header>
      <img src={logoImg} alt="" className="logo" />
      <div className="right">
        <Dropdown overlay={menu}>
          <a onClick={(e) => e.preventDefault()} className="ant-dropdown-link">
            <Space>
              <img className="avatar" src={avatar} alt="" />
              <span>{userName}</span>
              <CaretDownOutlined />
            </Space>
          </a>
        </Dropdown>
      </div>
    </header>
  );
}
